package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.xing.config.JSONUtils;
import com.xing.dao.SysMenuDao;
import com.xing.dao.SysUserDao;
import com.xing.entity.SysUserEntity;
import com.xing.service.SysUserDetailService;
import com.xing.user.User;
import com.xing.user.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/12/3 22:14
 */
@Service
public class SysUserDetailServiceImpl implements SysUserDetailService {
    @Autowired
    private SysUserDao userDao;
    @Autowired
    private SysMenuDao menuDao;
    @Override
    public UserDetail getUserDetailById(Long id) throws Exception {
        SysUserEntity sysUserEntity = userDao.selectById(id);
        UserDetail userDetail = new UserDetail();
        User user = new User();
        User entity = JSONUtils.objParse(sysUserEntity,user.getClass());
        userDetail.setUser(entity);
        initUserData(userDetail);
        return userDetail;
    }

    @Override
    public UserDetail getUserDetailByUsername(String username) throws Exception {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUserEntity sysUserEntity = userDao.selectOne(wrapper);
        UserDetail userDetail = new UserDetail();
        User user = new User();
        if (sysUserEntity ==null){
            return userDetail;
        }
        User entity = JSONUtils.objParse(sysUserEntity,User.class);
        userDetail.setUser(entity);
        initUserData(userDetail);
        return userDetail;
    }

    /**
     * 初始化用户数据
     */
    private void initUserData(UserDetail userDetail) {
        if (userDetail == null) {
            return;
        }
        List<String> perms = menuDao.selectPermsByUserId(userDetail.getUser().getId());
        userDetail.getUser().setPower(perms);
    }
}
